package com.fc.advbox.controller.open;

import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.dto.open.PublicTokenRespDto;
import com.fc.advbox.dto.user.UserPointDto;
import com.fc.advbox.entity.PublicTokenEntity;
import com.fc.advbox.entity.UserPointEntity;
import com.fc.advbox.service.IPublicTokenService;
import com.fc.advbox.service.IUserPointService;
import com.fc.advbox.utils.DateTimeHelper;
import com.fc.advbox.utils.RRException;
import com.fc.advbox.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Description:
 * User: Charles.Gao
 * Date: 2018-07-19 16:16
 */
@RestController
@RequestMapping("/api/oauth")
@Api(value="开放认证接口- 用于第三方应用调用相关的API", tags={"开放认证接口"})
public class OAuthController {

    private static final int PUB_TOKEN_EXPIRE_SECOND = 3600;
    private final IUserPointService userPointService;
    private final IPublicTokenService publicTokenService;
    @Autowired
    public OAuthController(IUserPointService userPointService, IPublicTokenService publicTokenService) {
        this.userPointService = userPointService;
        this.publicTokenService = publicTokenService;
    }

    @ApiOperation(value = "GET -- 获取授权令牌",
            notes = " REST 方式请求" +
                    "<li><i>必填参数: appid: 应用ID</i></li>" +
                    "<li><i>必填参数: secret: 应用秘钥</i></li>" +
                    "</ul>")
    @GetMapping("/accesstoken")
    public ResponseJson doOAuth(@RequestParam String appid, @RequestParam String secret) {
        PublicTokenRespDto publicToken = new PublicTokenRespDto();
        Map<String, Object> params = new HashMap<>();
        params.put("appId", appid);
        params.put("secret", secret);
        PublicTokenEntity tokenEntity = publicTokenService.queryObject(params);
        if(tokenEntity == null){
            return ResponseJson.error(ResponseJson.CODE_403,"未授权的应用");
        }

        String token = DigestUtils.md2Hex(StringUtils.createLinkString(params));

        tokenEntity.setAccessToken(token);
        tokenEntity.setCreateTime(new Date());
        tokenEntity.setExpireTime(DateTimeHelper.addHours(new Date(), PUB_TOKEN_EXPIRE_SECOND/3600));

        publicTokenService.update(tokenEntity);

        publicToken.setToken(token);
        publicToken.setExpiresIn(PUB_TOKEN_EXPIRE_SECOND);
        return ResponseJson.success(publicToken);
    }




}
